{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h1 align=\"center\"> Registration Initialization: We Have to Start Somewhere</h1>\n",
    "\n",
    "Initialization is a critical aspect of most registration algorithms, given that most algorithms are formulated as an iterative optimization problem. It effects both the runtime and convergence to the correct minimum. Ideally our transformation is initialized close to the correct solution ensuring convergence in a timely manner. Problem specific initialization will often yield better results than generic initialization approaches. \n",
    "\n",
    "**Rule of thumb**: use as much prior information (external to the image content) as you can to initialize your registration.\n",
    "\n",
    "Common initializations strategies when no prior information is available:\n",
    "1. Do nothing (hope springs eternal) - initialize using the identity transformation.\n",
    "2. CenteredTransformInitializer (GEOMETRY or MOMENTS) - translation based initialization, align the geometric centers of the images or the intensity based centers of mass of the image contents.\n",
    "3. Use a sampling of the parameter space (useful mostly for low dimensional parameter spaces).\n",
    "4. Manual initialization - allow an operator to control transformation parameter settings directly using a GUI with visual feedback or identify multiple corresponding points in the two images and compute an initial rigid or affine transformation. \n",
    "\n",
    "\n",
    "In many cases we perform initialization in an automatic manner by making assumptions with regard to the contents of the image and the imaging protocol. For instance, if we expect that images were acquired with the patient in a known orientation we can align the geometric centers of the two volumes or the center of mass of the image contents if the anatomy is not centered in the image (this is what we previously did in [this example](60_Registration_Introduction.ipynb)).\n",
    "\n",
    "When the orientation is not known, or is known but incorrect, this approach will not yield a reasonable initial estimate for the registration.\n",
    "\n",
    "When working with clinical images, the DICOM tags define the orientation and position of the anatomy in the volume. The tags of interest are:\n",
    "<ul>\n",
    "  <li> (0020|0032) Image Position (Patient) : coordinates of the the first transmitted voxel. </li>\n",
    "  <li>(0020|0037) Image Orientation (Patient): directions of first row and column in 3D space. </li>\n",
    "  <li>(0018|5100) Patient Position: Patient placement on the table \n",
    "  <ul>\n",
    "  <li> Head First Prone (HFP)</li>\n",
    "  <li> Head First Supine (HFS)</li>\n",
    "  <li> Head First Decubitus Right (HFDR)</li>\n",
    "  <li> Head First Decubitus Left (HFDL)</li>\n",
    "  <li> Feet First Prone (FFP)</li>\n",
    "  <li> Feet First Supine (FFS)</li>\n",
    "  <li> Feet First Decubitus Right (FFDR)</li>\n",
    "  <li> Feet First Decubitus Left (FFDL)</li>\n",
    "  </ul>\n",
    "  </li>\n",
    "</ul>\n",
    "\n",
    "The patient position is manually entered by the CT/MR operator and thus can be erroneous (HFP instead of FFP will result in a $180^o$ orientation error). In this notebook we use data acquired using an abdominal phantom which made it hard to identify the \"head\" and \"feet\" side, resulting in an incorrect value entered by the technician. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import SimpleITK as sitk\n",
    "\n",
    "# If the environment variable SIMPLE_ITK_MEMORY_CONSTRAINED_ENVIRONMENT is set, this will override the ReadImage\n",
    "# function so that it also resamples the image to a smaller size (testing environment is memory constrained).\n",
    "%run setup_for_testing\n",
    "\n",
    "import os\n",
    "import numpy as np\n",
    "\n",
    "from ipywidgets import interact, fixed\n",
    "%run update_path_to_download_script\n",
    "from downloaddata import fetch_data as fdata\n",
    "\n",
    "%matplotlib notebook\n",
    "import gui\n",
    "\n",
    "# This is the registration configuration which we use in all cases. The only parameter that we vary \n",
    "# is the initial_transform. \n",
    "def multires_registration(fixed_image, moving_image, initial_transform):\n",
    "    registration_method = sitk.ImageRegistrationMethod()\n",
    "    registration_method.SetMetricAsMattesMutualInformation(numberOfHistogramBins=50)\n",
    "    registration_method.SetMetricSamplingStrategy(registration_method.RANDOM)\n",
    "    registration_method.SetMetricSamplingPercentage(0.01)\n",
    "    registration_method.SetInterpolator(sitk.sitkLinear)\n",
    "    registration_method.SetOptimizerAsGradientDescent(learningRate=1.0, numberOfIterations=100, estimateLearningRate=registration_method.Once)\n",
    "    registration_method.SetOptimizerScalesFromPhysicalShift() \n",
    "    registration_method.SetInitialTransform(initial_transform, inPlace=False)\n",
    "    registration_method.SetShrinkFactorsPerLevel(shrinkFactors = [4,2,1])\n",
    "    registration_method.SetSmoothingSigmasPerLevel(smoothingSigmas = [2,1,0])\n",
    "    registration_method.SmoothingSigmasAreSpecifiedInPhysicalUnitsOn()\n",
    "\n",
    "    final_transform = registration_method.Execute(fixed_image, moving_image)\n",
    "    print('Final metric value: {0}'.format(registration_method.GetMetricValue()))\n",
    "    print('Optimizer\\'s stopping condition, {0}'.format(registration_method.GetOptimizerStopConditionDescription()))\n",
    "    return (final_transform, registration_method.GetMetricValue())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Loading Data\n",
    "\n",
    "**Note**: While the images are of the same phantom, they were acquired at different times and the fiducial markers visible on the phantom are not in the same locations.\n",
    "\n",
    "Scroll through the data to gain an understanding of the spatial relationship along the viewing (z) axis."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_directory = os.path.dirname(fdata(\"CIRS057A_MR_CT_DICOM/readme.txt\"))\n",
    "\n",
    "fixed_series_ID = \"1.2.840.113619.2.290.3.3233817346.783.1399004564.515\"\n",
    "moving_series_ID = \"1.3.12.2.1107.5.2.18.41548.30000014030519285935000000933\"\n",
    "\n",
    "reader = sitk.ImageSeriesReader()\n",
    "fixed_image = sitk.ReadImage(reader.GetGDCMSeriesFileNames(data_directory, fixed_series_ID), sitk.sitkFloat32)\n",
    "moving_image = sitk.ReadImage(reader.GetGDCMSeriesFileNames(data_directory, moving_series_ID), sitk.sitkFloat32)\n",
    "\n",
    "# To provide a reasonable display we need to window/level the images. By default we could have used the intensity\n",
    "# ranges found in the images [SimpleITK's StatisticsImageFilter], but these are not the best values for viewing.\n",
    "# Using an external viewer we identified the following settings.\n",
    "ct_window_level = [1727,-320]\n",
    "mr_window_level = [355,178]\n",
    "\n",
    "gui.MultiImageDisplay(image_list = [fixed_image, moving_image],                   \n",
    "                      title_list = ['fixed image', 'moving image'], figure_size=(8,4), window_level_list=[ct_window_level, mr_window_level]);\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Register using centered transform initializer  (assumes orientation is similar)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "initial_transform = sitk.CenteredTransformInitializer(fixed_image, \n",
    "                                                      moving_image, \n",
    "                                                      sitk.Euler3DTransform(), \n",
    "                                                      sitk.CenteredTransformInitializerFilter.GEOMETRY)\n",
    "\n",
    "final_transform,_ = multires_registration(fixed_image, moving_image, initial_transform)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Visually evaluate the results using a linked cursor approach, a mouse click in one image will create the \"corresponding\" point in the other image. Don't be fooled by clicking on the \"ribs\" (symmetry is the bane of registration)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gui.RegistrationPointDataAquisition(fixed_image, moving_image, figure_size=(8,4), \n",
    "                                    known_transformation=final_transform, \n",
    "                                    fixed_window_level=ct_window_level, moving_window_level=mr_window_level);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Register using sampling of the parameter space\n",
    "\n",
    "As we want to account for significant orientation differences due to erroneous patient position (HFS...) we evaluate the similarity measure at locations corresponding to the various orientation differences. This can be done in two ways which will be illustrated below:\n",
    "<ul>\n",
    "<li>Use the ImageRegistrationMethod.MetricEvaluate() method.</li>\n",
    "<li>Use the Exhaustive optimizer.\n",
    "</ul>\n",
    "\n",
    "The former approach is more computationally intensive as it constructs and configures a metric object each time it is invoked. It is therefore more appropriate for use if the set of parameter values we want to evaluate are not on a rectilinear grid in the parameter space. The latter approach is appropriate if the set of parameter values are on a rectilinear grid, in which case the approach is more computationally efficient.\n",
    "\n",
    "In both cases we use the CenteredTransformInitializer to obtain the initial translation."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### MetricEvaluate\n",
    "\n",
    "To use the MetricEvaluate method we create a ImageRegistrationMethod, set its metric and interpolator. We then iterate over all parameter settings, set the initial transform and evaluate the metric. The minimal similarity measure value corresponds to the best parameter settings."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Dictionary with all the orientations we will try. We omit the identity (x=0, y=0, z=0) as we always use it. This\n",
    "# set of rotations is arbitrary. For a complete grid coverage we would naively have 64 entries \n",
    "# (0, pi/2, pi, 1.5pi for each angle), but we know better, there are only 24 unique rotation matrices defined by\n",
    "# these parameter value combinations.\n",
    "all_orientations = {'x=0, y=0, z=180': (0.0,0.0,np.pi),\n",
    "                    'x=0, y=180, z=0': (0.0,np.pi, 0.0),\n",
    "                    'x=0, y=180, z=180': (0.0,np.pi, np.pi)}    \n",
    "\n",
    "# Registration framework setup.\n",
    "registration_method = sitk.ImageRegistrationMethod()\n",
    "registration_method.SetMetricAsMattesMutualInformation(numberOfHistogramBins=50)\n",
    "registration_method.SetMetricSamplingStrategy(registration_method.RANDOM)\n",
    "registration_method.SetMetricSamplingPercentage(0.01)\n",
    "registration_method.SetInterpolator(sitk.sitkLinear)\n",
    "\n",
    "# Evaluate the similarity metric using the rotation parameter space sampling, translation remains the same for all.\n",
    "initial_transform = sitk.Euler3DTransform(sitk.CenteredTransformInitializer(fixed_image, \n",
    "                                                                            moving_image, \n",
    "                                                                            sitk.Euler3DTransform(), \n",
    "                                                                            sitk.CenteredTransformInitializerFilter.GEOMETRY))\n",
    "registration_method.SetInitialTransform(initial_transform, inPlace=False)\n",
    "best_orientation = (0.0,0.0,0.0)\n",
    "best_similarity_value = registration_method.MetricEvaluate(fixed_image, moving_image)\n",
    "\n",
    "# Iterate over all other rotation parameter settings. \n",
    "for key, orientation in all_orientations.items():\n",
    "    initial_transform.SetRotation(*orientation)\n",
    "    registration_method.SetInitialTransform(initial_transform)\n",
    "    current_similarity_value = registration_method.MetricEvaluate(fixed_image, moving_image)\n",
    "    if current_similarity_value < best_similarity_value:\n",
    "        best_similarity_value = current_similarity_value\n",
    "        best_orientation = orientation\n",
    "print('best orientation is: ' + str(best_orientation))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Why loop if you can process in parallel\n",
    "As the metric evaluations are independent of each other, we can easily replace looping with parallelization. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from multiprocessing.pool import ThreadPool\n",
    "from functools import partial\n",
    "\n",
    "# This function evaluates the metric value in a thread safe manner\n",
    "def evaluate_metric(current_rotation, tx, f_image, m_image):\n",
    "    registration_method = sitk.ImageRegistrationMethod()\n",
    "    registration_method.SetMetricAsMattesMutualInformation(numberOfHistogramBins=50)\n",
    "    registration_method.SetMetricSamplingStrategy(registration_method.RANDOM)\n",
    "    registration_method.SetMetricSamplingPercentage(0.01)\n",
    "    registration_method.SetInterpolator(sitk.sitkLinear)\n",
    "    current_transform = sitk.Euler3DTransform(tx)\n",
    "    current_transform.SetRotation(*current_rotation)\n",
    "    registration_method.SetInitialTransform(current_transform)\n",
    "    res = registration_method.MetricEvaluate(f_image, m_image)\n",
    "    return res\n",
    "\n",
    "p = ThreadPool(len(all_orientations)+1)\n",
    "orientations_list = [(0,0,0)] + list(all_orientations.values())\n",
    "all_metric_values = p.map(partial(evaluate_metric, \n",
    "                                  tx = initial_transform, \n",
    "                                  f_image = fixed_image,\n",
    "                                  m_image = moving_image),\n",
    "                          orientations_list)\n",
    "best_orientation = orientations_list[np.argmin(all_metric_values)]\n",
    "print('best orientation is: ' + str(best_orientation))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "initial_transform.SetRotation(*best_orientation)\n",
    "final_transform,_ = multires_registration(fixed_image, moving_image, initial_transform)  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Visually evaluate the registration results:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gui.RegistrationPointDataAquisition(fixed_image, moving_image, figure_size=(8,4), \n",
    "                                    known_transformation=final_transform, \n",
    "                                    fixed_window_level=ct_window_level, moving_window_level=mr_window_level);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exhaustive optimizer\n",
    "\n",
    "The exhaustive optimizer evaluates the similarity metric on a grid in parameter space centered on the parameters of the initial transform. This grid is defined using three elements:\n",
    "1. numberOfSteps.\n",
    "2. stepLength.\n",
    "3. optimizer scales.\n",
    "\n",
    "The similarity metric is evaluated on the resulting parameter grid:\n",
    "initial_parameters &plusmn; numberOfSteps &times; stepLength &times; optimizerScales\n",
    "\n",
    "***Example***:\n",
    "1. numberOfSteps=[1,0,2,0,0,0]\n",
    "2. stepLength = np.pi\n",
    "3. optimizer scales = [1,1,0.5,1,1,1]\n",
    "\n",
    "Will perform 15 metric evaluations ($\\displaystyle\\prod_i (2*numberOfSteps[i] + 1)$).\n",
    "\n",
    "The parameter values for the second parameter and the last three parameters are the initial parameter values. The parameter values for the first parameter are $v_{init}-\\pi, v_{init}, v_{init}+\\pi$ and the parameter values for the third parameter are $v_{init}-\\pi, v_{init}-\\pi/2, v_{init}, v_{init}+\\pi/2, v_{init}+\\pi$.\n",
    "\n",
    "The transformation corresponding to the lowest similarity metric is returned.\n",
    "\n",
    "Using this approach we have superfluous evaluations, due to the symmetry of the grid in parameter space. On the other hand this method is often faster than evaluating the metric using the `MetricEvaluate` method (due to the setup and tear down time).  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "initial_transform = sitk.CenteredTransformInitializer(fixed_image, \n",
    "                                                      moving_image, \n",
    "                                                      sitk.Euler3DTransform(), \n",
    "                                                      sitk.CenteredTransformInitializerFilter.GEOMETRY)\n",
    "registration_method = sitk.ImageRegistrationMethod()\n",
    "registration_method.SetMetricAsMattesMutualInformation(numberOfHistogramBins=50)\n",
    "registration_method.SetMetricSamplingStrategy(registration_method.RANDOM)\n",
    "registration_method.SetMetricSamplingPercentage(0.01)\n",
    "registration_method.SetInterpolator(sitk.sitkLinear)\n",
    "# The order of parameters for the Euler3DTransform is [angle_x, angle_y, angle_z, t_x, t_y, t_z]. The parameter \n",
    "# sampling grid is centered on the initial_transform parameter values, that are all zero for the rotations. Given\n",
    "# the number of steps and their length and optimizer scales we have:\n",
    "# angle_x = 0\n",
    "# angle_y = -pi, 0, pi\n",
    "# angle_z = -pi, 0, pi\n",
    "registration_method.SetOptimizerAsExhaustive(numberOfSteps=[0,1,1,0,0,0], stepLength = np.pi)\n",
    "registration_method.SetOptimizerScales([1,1,1,1,1,1])\n",
    "\n",
    "#Perform the registration in-place so that the initial_transform is modified.\n",
    "registration_method.SetInitialTransform(initial_transform, inPlace=True)\n",
    "registration_method.Execute(fixed_image, moving_image)\n",
    "\n",
    "print('best initial transformation is: ' + str(initial_transform.GetParameters()))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Run the registration and visually evaluate the results:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "final_transform, _ = multires_registration(fixed_image, moving_image, initial_transform)\n",
    "gui.RegistrationPointDataAquisition(fixed_image, moving_image, figure_size=(8,4), \n",
    "                                    known_transformation=final_transform, \n",
    "                                    fixed_window_level=ct_window_level, moving_window_level=mr_window_level);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exhaustive optimizer - an exploration-exploitation view\n",
    "\n",
    "In the example above we used the exhaustive optimizer to obtain an initial value for our transformation parameter values. This approach has two limitations:\n",
    "1. It assumes we only want to sample the parameter space using a continuous regular grid. This is not appropriate if we want to explore multiple discontinuous regions of the parameter space (e.g. tx = [0.5, 1.0, 1.5] and tx = [ 12.0, 12.5, 13.0] and...).\n",
    "2. It assumes that the parameter values corresponding to the best metric value from our sample will enable convergence to the desired optimum. To quote [George Gershwin](https://en.wikipedia.org/wiki/George_Gershwin) - \"It Ain't Necessarily So\". \n",
    "\n",
    "If we consider the exhaustive optimizer in the context of the exploration-exploitation heuristic framework, we first search the parameter space for promising solution(s) and then refine the solution(s), we can readily address these limitations:\n",
    "\n",
    "1. Explore multiple discontinuous regions using a single or multiple instances of the ExhaustiveOptimizer or use the MetricEvaluate approach if the samples do not define a regular grid.\n",
    "2. Obtain *all* of the parameter space samples and exploit (run final registration) for each of the k most promising solutions.\n",
    "\n",
    "Below we implement the latter: (a) We explore the parameter space using the exhaustive optimizer's callback mechanism to obtain all of the parameter values and their corresponding metric values. (b) We exploit the k_most_promising parameter values to obtain the final transformation.\n",
    "\n",
    "**NOTE**: This is a heuristic and only increases the probability of convergence to the desired optimum. In some cases this approach may be detrimental when the parameter values we seek correspond to a local optimum and not a global one."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#\n",
    "# Exploration step.\n",
    "#\n",
    "def start_observer():\n",
    "    global metricvalue_parameters_list \n",
    "    metricvalue_parameters_list = []\n",
    "\n",
    "def iteration_observer(registration_method):    \n",
    "    metricvalue_parameters_list.append((registration_method.GetMetricValue(), registration_method.GetOptimizerPosition()))\n",
    "    \n",
    "initial_transform = sitk.CenteredTransformInitializer(fixed_image, \n",
    "                                                      moving_image, \n",
    "                                                      sitk.Euler3DTransform(), \n",
    "                                                      sitk.CenteredTransformInitializerFilter.GEOMETRY)\n",
    "registration_method = sitk.ImageRegistrationMethod()\n",
    "registration_method.SetMetricAsMattesMutualInformation(numberOfHistogramBins=50)\n",
    "registration_method.SetMetricSamplingStrategy(registration_method.RANDOM)\n",
    "registration_method.SetMetricSamplingPercentage(0.01)\n",
    "registration_method.SetInterpolator(sitk.sitkLinear)\n",
    "# The order of parameters for the Euler3DTransform is [angle_x, angle_y, angle_z, t_x, t_y, t_z]. The parameter \n",
    "# sampling grid is centered on the initial_transform parameter values, that are all zero for the rotations. Given\n",
    "# the number of steps and their length and optimizer scales we have:\n",
    "# angle_x = 0\n",
    "# angle_y = -pi, 0, pi\n",
    "# angle_z = -pi, 0, pi\n",
    "registration_method.SetOptimizerAsExhaustive(numberOfSteps=[0,1,1,0,0,0], stepLength = np.pi)\n",
    "registration_method.SetOptimizerScales([1,1,1,1,1,1])\n",
    "\n",
    "#We don't really care if transformation is modified in place or not, we will select the k \n",
    "#best transformations from the parameters_metricvalue_list.\n",
    "registration_method.SetInitialTransform(initial_transform, inPlace=True)\n",
    "\n",
    "registration_method.AddCommand(sitk.sitkIterationEvent, lambda: iteration_observer(registration_method))\n",
    "registration_method.AddCommand(sitk.sitkStartEvent, start_observer )\n",
    "_ = registration_method.Execute(fixed_image, moving_image)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#\n",
    "# Exploitation step.\n",
    "#\n",
    "\n",
    "#Sort our list from most to least promising solutions (low to high metric values). \n",
    "metricvalue_parameters_list.sort(key=lambda x: x[0]) \n",
    "\n",
    "# We exploit the k_most_promising parameter value settings.\n",
    "k_most_promising = min(3, len(metricvalue_parameters_list))\n",
    "final_results = []\n",
    "for metricvalue, parameters in metricvalue_parameters_list[0:k_most_promising]:\n",
    "    initial_transform.SetParameters(parameters)\n",
    "    final_results.append(multires_registration(fixed_image, moving_image, initial_transform))\n",
    "\n",
    "final_transform, _ = min(final_results, key=lambda x: x[1]) \n",
    "gui.RegistrationPointDataAquisition(fixed_image, moving_image, figure_size=(8,4), \n",
    "                                    known_transformation=final_transform, \n",
    "                                    fixed_window_level=ct_window_level, moving_window_level=mr_window_level);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Register using manual initialization\n",
    "\n",
    "When all else fails, a human in the loop will almost always be able to robustly initialize the registration.\n",
    "\n",
    "In the example below we identify corresponding points to compute an initial rigid transformation. You will need to click on corresponding points in each of the images, going back and forth between them. The interface will \"force\" you to create point pairs (you will not be able to add multiple points in one image). \n",
    "\n",
    "**Note**: \n",
    "1. There is no correspondence between the fiducial markers on the phantom.\n",
    "2. After localizing points in the GUI below, comment out the hard-coded point data, two cells below, which is there FOR TESTING."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "point_acquisition_interface = gui.RegistrationPointDataAquisition(fixed_image, moving_image, figure_size=(8,4), \n",
    "                                                                  fixed_window_level=ct_window_level, \n",
    "                                                                  moving_window_level=mr_window_level);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Get the manually specified points and compute the transformation.\n",
    "\n",
    "fixed_image_points, moving_image_points = point_acquisition_interface.get_points()\n",
    "\n",
    "# FOR TESTING: previously localized points\n",
    "fixed_image_points = [(24.062587103074605, 14.594981536981521, -58.75), \n",
    "                      (6.178716135332678, 53.93949766601378, -58.75), \n",
    "                      (74.14383149714774, -69.04462737237648, -76.25), \n",
    "                      (109.74899278747029, -14.905272533666817, -76.25)]\n",
    "moving_image_points = [(4.358707846364581, 60.46357110706131, -71.53120422363281), \n",
    "                       (24.09010295252645, 98.21840981673873, -71.53120422363281), \n",
    "                       (-52.11888008581127, -26.57984635768439, -58.53120422363281), \n",
    "                       (-87.46150681392184, 28.73904765153219, -58.53120422363281)]\n",
    "\n",
    "fixed_image_points_flat = [c for p in fixed_image_points for c in p]        \n",
    "moving_image_points_flat = [c for p in moving_image_points for c in p]\n",
    "initial_transform = sitk.LandmarkBasedTransformInitializer(sitk.VersorRigid3DTransform(), \n",
    "                                                                fixed_image_points_flat, \n",
    "                                                                moving_image_points_flat)\n",
    "\n",
    "\n",
    "print('manual initial transformation is: ' + str(initial_transform.GetParameters()))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Run the registration and visually evaluate the results:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "final_transform = multires_registration(fixed_image, moving_image, initial_transform)\n",
    "gui.RegistrationPointDataAquisition(fixed_image, moving_image, figure_size=(8,4), \n",
    "                                    known_transformation=final_transform, \n",
    "                                    fixed_window_level=ct_window_level, moving_window_level=mr_window_level);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
